import { useCallback } from 'react';
import { toast } from '../stores/toastStore';
import type { ApiError } from '../api/types';

/**
 * API错误处理的hook - 支持丰富错误信息和处理建议
 */
export function useApiError() {
  const handleError = useCallback((error: ApiError | unknown, customMessage?: string) => {
    console.error('API Error:', error);

    // 如果是标准化的ApiError
    if (error && typeof error === 'object' && 'code' in error && 'msg' in error) {
      const apiError = error as ApiError;

      // 🚨 优先使用后端返回的错误消息，只有在没有自定义消息时才考虑状态码映射
      let displayMessage = customMessage || apiError.msg;

      // 🚨 只有在没有自定义消息且后端消息为空或通用时，才使用状态码映射
      const shouldUseStatusCodeMapping =
        !customMessage &&
        (!apiError.msg ||
          apiError.msg === '操作失败' ||
          apiError.msg === '请求失败' ||
          apiError.msg.trim() === '');

      // 特殊错误码的定制化消息
      switch (apiError.code) {
        case 401:
          if (shouldUseStatusCodeMapping) {
            displayMessage = '登录已过期或凭据无效，请重新登录';
          }
          break;
        case 403:
          if (shouldUseStatusCodeMapping) {
            displayMessage = '您没有权限执行此操作';
          }
          break;
        case 404:
          if (shouldUseStatusCodeMapping) {
            displayMessage = '请求的资源不存在或已被删除';
          }
          break;
        case 422:
          if (shouldUseStatusCodeMapping) {
            displayMessage = '输入数据格式不正确，请检查后重试';
          }
          break;
        case 429:
          if (shouldUseStatusCodeMapping) {
            displayMessage = '操作过于频繁，请稍后再试';
          }
          break;
        case 500:
          if (shouldUseStatusCodeMapping) {
            displayMessage = '服务器内部错误，请稍后重试';
          }
          break;
        case 0:
          if (shouldUseStatusCodeMapping) {
            displayMessage = '网络连接失败，请检查网络连接';
          }
          break;
        default:
          // 对于其他状态码，优先使用后端返回的消息
          if (!customMessage && apiError.code >= 400) {
            displayMessage = apiError.msg || '操作失败';
          }
      }

      // 🚨 简化错误显示 - 只显示错误消息，不显示复杂的详情和建议
      toast.error(displayMessage);

      return apiError;
    }

    // 处理其他类型的错误 - 简化显示
    const fallbackMessage = customMessage || '操作失败，请稍后重试';
    let errorMessage = fallbackMessage;

    if (error && typeof error === 'object') {
      const err = error as { message?: string };
      errorMessage = err.message || error.toString() || fallbackMessage;
    }

    // 🚨 简化显示 - 只显示错误消息
    toast.error(errorMessage);

    return {
      code: 0,
      msg: errorMessage,
      timestamp: new Date().toISOString(),
    } as ApiError;
  }, []);

  const handleSuccess = useCallback((message: string) => {
    toast.success(message);
  }, []);

  const handleInfo = useCallback((message: string) => {
    toast.info(message);
  }, []);

  const handleWarning = useCallback((message: string) => {
    toast.warning(message);
  }, []);

  return {
    handleError,
    handleSuccess,
    handleInfo,
    handleWarning,
  };
}
